const router = require('express').Router();
const { dbQuery, dbError, sqlStrQuotationHandle } = require('../../tools');
const socketio = require('../../socket');
const fs = require('fs');
const pathLib = require('path');
const { client } = require('../../redis');

router.get('/name', function(req, res) {
    const {group_id, group_name} = req.query;
	const nameStr = sqlStrQuotationHandle(group_name);

	dbQuery(`update group_table set group_name='${nameStr}' where group_id='${group_id}'`)
	.then(() => {
		dbQuery(`select * from group_table where group_id='${group_id}'`)
		.then(data => {
            // 发送socket通知更改groupList的群组名称
            socketio().sockets.to(`room${group_id}`).emit(
				`roomMessage${group_id}`, 
				{
					type: 'change',
					data: {
                        group_name: nameStr
					}
				}
			);
            res.send({code: 1,message: '修改成功', data: data[0]});
		});
	})
	.catch(err => {
		dbError(res, err, '修改名称失败');
	});
});
router.get('/intro', function(req, res) {
    const {group_id, group_intro} = req.query;
	const nameStr = sqlStrQuotationHandle(group_intro);
	dbQuery(`update group_table set group_intro='${nameStr}' where group_id='${group_id}'`)
	.then(() => {
		dbQuery(`select * from group_table where group_id='${group_id}'`)
		.then(data => {
            res.send({code: 1,message: '修改成功', data: data[0]});
		});
	})
	.catch(err => {
		dbError(res, err, '修改名称失败');
	});
});
router.post('/avator', function(req, res) {
	if (!req.files || req.files.length < 1) {
		res.send({code: 0, message: '无上传文件'});
		return;
	}
	const {group_id} = req.body;
	const file = req.files[0];
	const avatorFolder = 'img/group_avator/'

	// 修改头像路径
	const finalAvatorUrl = `${file.destination}/${avatorFolder}${file.filename}${pathLib.parse(file.originalname).ext}`;
	new Promise((resolve, reject) => {
		// 修改上传文件名
		fs.rename(
			file.path,
			finalAvatorUrl,
			function(err) {
				if (err) {
					console.log(err);
					reject(err);
				}
				resolve();
		});
	})
	.then(() => {
		let updateSQL = () => new Promise((resolve, reject) => {
			// 更新数据库头像路径
			dbQuery(`update group_table set group_avator='${finalAvatorUrl.split('./static/')[1]}' where group_id='${group_id}'`)
			.then(() => {
				resolve('数据库更新完成');
			})
			.catch((err) => {
				console.log(err, '79');
				reject('数据库更新错误');
			});
		});
		let originAvatorDel = () => new Promise((resolve, reject) => {
			// 删除原头像
			dbQuery(`select group_avator from group_table where group_id='${group_id}'`)
			.then(data => {
				const imgUrl = data[0].group_avator;
				if (imgUrl === `${avatorFolder}group.jpg`) {
					return resolve('默认头像不删除');
				}
				fs.unlink(`./static/${imgUrl}`, function() {
					resolve('原头像删除完成');
				});
			})
			.catch(err => {				
				console.log(err, '97');
				reject('查询删除头像错误');
			});
		});

		// 删除原头像,更改数据库数据,都完成后发送res,
		originAvatorDel().then(() => updateSQL())
		.then(() => {
			// 头像和数据库处理完成,获取新群组信息发送
			async function getAdminInfo(userIdStr) {
				// 获取群组管理员id和头像
				return await dbQuery(`select id as user_id, avator as user_avator from user_table where id in (${userIdStr})`);
			}
			dbQuery(`
				select 
					g.group_id,g.group_name,g.group_avator,g.group_intro,g.admin,g.create_time,g.creator_id,g.group_public,count(m.user_id) as people_num
				from 
					group_table g,
					member_table m
				where
					g.group_id='${group_id}' and m.group_id='${group_id}'
			`)
			.then(async groupData => {
				const adminInfo = await getAdminInfo(groupData[0].admin);
				socketio().sockets.to(`room${group_id}`).emit(
					`roomMessage${group_id}`, 
					{
						type: 'change',
						data: {
							group_avator: groupData[0].group_avator
						}
					}
				);
				res.send({code: 1, message: '请求成功', data: { ...groupData[0], admin: adminInfo }});
			})
			.catch(err => {
				dbError(res, err);
			});


		})
		.catch(err => {
			dbError(res, err);
		});

	})
	.catch(err => {
		console.log(err, file.path);
		// 修改上传文件路径失败,删除临时文件
		fs.unlink(file.path, function(err) {
			if (err) {
				console.log('上传临时文件删除失败');
			}
		});
		res.send({code: 0, message: '数据库错误'});
		return;
	});
});
router.get('/set', function(req, res) {
	const {group_id,attr,value} = req.query;

	let attribute = '';
	switch(attr) {
		case 'public':
			attribute = 'group_public';
			break;
		default:
			res.send({code: 0, message: '参数错误'});
			return;
			break;
	}

	dbQuery(`update group_table set ${attribute}='${value}' where group_id='${group_id}'`)
	.then(data => {
		res.send({code: 1, message: '更改成功'});
	})
	.catch(err => {
		dbError(res, err);
	});
});
router.get('/creator', function(req, res) {

	const {group_id,user_id,target_id} = req.query;

	function transferCreator() {
		dbQuery(`update user_table set can_create=can_create+1 where id='${user_id}'`)
		.catch(err => {
			console.log(err);
			console.log('移交群组后可创建群组数增加失败');
		});
		
		dbQuery(`update group_table set creator_id='${target_id}', admin=concat(admin, ',${target_id}') where group_id='${group_id}'`)
		.then(() => {
			sendSystemMessage();
			res.send({code: 1, message: '更新成功'});
		})
		.catch(err => {
			dbError(res, err);
		});
	}
	function sendSystemMessage() {
		// 向成为群主的用户发送系统消息
		dbQuery(`select group_name from group_table where group_id='${group_id}'`)
		.then(data => {
			dbQuery(`
				insert into system_message_table 
				(user_id,message_content,message_type) 
				values 
				('${target_id}','你已成为群组${data[0].group_name}的管理员','0')
			`)
			.then(insertData => {
				socketio().emit(`systemMessage${target_id}`, {
					name:'系统消息',
					avator: 'system_message',
					checked: 0,
					message_type: '0',
					message_content: `你已成为群组${data[0].group_name}的管理员`,
					send_time: new Date(),
					user_id: +target_id,
					message_id: insertData.insertId
				});
			});
		});
	}

	client.get(user_id, (err, value) => {
		if (req.session.id === value) {
			// 是群主请求才进行操作
			transferCreator();
		} else {
			res.send({code: 0, message: '需要群主进行操作'});
		}
	});
});
router.get('/admin', function(req, res) {
	const {group_id, user_id, target_id,set_type} = req.query;

	function sendSystemMessage() {
		// 向成为管理员的用户发送系统消息
		dbQuery(`select group_name from group_table where group_id='${group_id}'`)
		.then(data => {
			let message = '';
			if (set_type === 'set') {
				message = `你已成为群组${data[0].group_name}的管理员`;
			} else if (set_type === 'cancel') {
				message = `你被取消群组${data[0].group_name}的管理员权限`;
			}
			dbQuery(`
				insert into system_message_table 
				(user_id,message_content,message_type) 
				values 
				('${target_id}','${message}','0')
			`)
			.then(insertData => {
				socketio().emit(`systemMessage${target_id}`, {
					name:'系统消息',
					avator: 'system_message',
					checked: 0,
					message_type: '0',
					message_content: message,
					send_time: new Date(),
					user_id: +target_id,
					message_id: insertData.insertId
				});
			});
		});
	}
	function setUpAdmins(data) {
		const admins = data[0].admin.split(',');
		if (admins.length < 5) {
			dbQuery(`update group_table set admin=concat(admin,',${target_id}') where group_id='${group_id}'`)
			.then(() => {

				sendSystemMessage();
				
				res.send({code: 1, message: '设置管理员成功'});
			})
			.catch(err => {
				dbError(res, err);
			});
		} else {
			res.send({code: 0, message: '已到达管理员数目上限'});
		}
	}
	function cancelAdmins(data) {
		const admins = data[0].admin.split(',');
		for (let i = 0; i < admins.length; i++) {
			if (+admins[i] === +target_id) {
				admins.splice(i, 1);
				break;
			}
		}
		dbQuery(`update group_table set admin='${admins.join(',')}' where group_id='${group_id}'`)
		.then(() => {

			sendSystemMessage();
			
			res.send({code: 1, message: '设置管理员成功'});
		})
		.catch(err => {
			dbError(res, err);
		});
		
	}
	

	client.get(user_id, (err, value) => {
		if (req.session.id === value) {
			// 是群主请求才进行操作
			dbQuery(`select admin from group_table where group_id='${group_id}'`)
			.then(data => {
				if (set_type === 'set') {
					setUpAdmins(data);
				} else if (set_type === 'cancel') {
					cancelAdmins(data);
				}
			})
			.catch(err => {
				dbError(res, err);
			});
		} else {
			res.send({code: 0, message: '需要群主进行操作'});
		}
	});
});


module.exports = router;

